﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Raven.Client;
using CineProwl.Domain.Workers;

namespace CineProwl.Domain
{
    public class LibraryFolder
    {
        public string Path { get; set; }
        List<string> Folders { get; set; }

        public LibraryFolder(string path)
        {
            Path = path;
            Folders = new List<string>();
        }

        public List<Movie> ScanForNew(IDocumentSession ravenSession)
        {
            CheckDirectory();
            List<MovieFile> newMovieFiles = FindNewFiles(ravenSession);            
            List<Movie> newMovies = MovieInserter.InsertMovieFiles(ravenSession, newMovieFiles);

            ravenSession.SaveChanges();
            return newMovies;
        }

        private List<MovieFile> FindNewFiles(IDocumentSession ravenSession)
        {
            List<MovieFile> newMovieFiles = new List<MovieFile>();

            Folders = Directory.EnumerateDirectories(Path).ToList();
            foreach (string folder in Folders)
            {
                string filename = FileSystemService.FindMovieFile(folder);
                bool exists = ravenSession.Query<Movie>().Any(m => m.FileDetails.Path == filename);
                if (!exists)
                {
                    MovieFile fileInfo = FileSystemService.GetMovieFileFromFile(filename);
                    newMovieFiles.Add(fileInfo);
                }
            }
            return newMovieFiles;
        }

        private void CheckDirectory()
        {
            if (!Directory.Exists(Path))
            {
                throw new DirectoryNotFoundException("Library path of '" + Path + "' does not exist");
            }
        }

    }
}
